/**=========================================================
 * Directive: monthpicker-combine.js
 =========================================================*/

 tzadmin.directive('combineMonthpicker', ['Utils',
    function(utils) {
        'use strict';
        
        return {
            restrict: 'EA',
            replace: true,
            template: function($element,$attrs){
                var optionModel = utils.isEmpty($attrs.optionModel) ? 'monthRange' : $attrs.optionModel,
                    ngModel = 'combineMonthPickers.' + optionModel,
                    searchFn = utils.isEmpty($attrs.search) ? "search()" : $attrs.search;
                return '\
                    <table>\
                        <tr>\
                            <td style="padding:8px"><datepicker ng-model="' + ngModel + '.startMonth" format="yyyy-MM"></datepicker></td>\
                            <td style="padding:8px"><span class="control-label">~</span></td>\
                            <td style="padding:8px"><datepicker ng-model="' + ngModel + '.endMonth" format="yyyy-MM"></datepicker></td>\
                            <td style="padding:8px">\
                                <a class="btn btn-primary btn-search" ng-click="' + searchFn + '">\
                                    <i class="fa fa-search"></i>\
                                    {{$translate.instant("button.SEARCH")}}\
                                </a>\
                            </td>\
                        </tr>\
                    </table>\
                '
            },
            link: function($scope, $element, $attrs){
                var optionModel = utils.isEmpty($attrs.optionModel) ? 'monthRange' : $attrs.optionModel,
                    ngModel = 'combineMonthPickers.' + optionModel,
                    searchFn = utils.isEmpty($attrs.search) ? "search" : $attrs.search.substring(0,$attrs.search.indexOf('('));
  
                $scope.$watch(ngModel + ".startMonth.date", 
                    function (newVal, oldVal) {                       
                        $scope.combineMonthPickers[optionModel].endMonth.dateOptions.minDate = newVal;
                    }
                );
                
                $scope.$watch(ngModel + ".endMonth.date", 
                    function (newVal, oldVal) {                       
                        $scope.combineMonthPickers[optionModel].startMonth.dateOptions.maxDate = newVal;
                    }
                );
            }
        }
    }
]);
